package com.lsh.streamgd.task;

import com.lsh.streamgd.beans.TaskConfig;
import com.lsh.streamgd.dao.TaskRecord;
import com.lsh.streamgd.utils.Settings;
import com.lsh.streamgd.utils.StringUtil;
import com.lsh.streamgd.utils.TaskUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * Created by ljgsonx on 2017/1/14.
 */
@Component
public class DbTask {

    private static Logger logger = LoggerFactory.getLogger("DbTask");

//    @Scheduled(cron = "0/60 * * * * ?") //每10s执行 for test
    @Scheduled(cron = "0 0 * * * ?") //每小时执行
    public void pushJob() {
        Date now = new Date();
        logger.info("\n=====[  监听任务启动(Time:{})  ]======", StringUtil.formatDate(now));
        List<TaskConfig> taskConfigs = TaskRecord.getAllTaskConfigs(Settings.webappRoot + "taskConfig\\config.rdf");
        for (TaskConfig taskConfig : taskConfigs) {
            if (taskConfig.getStatus() == 1) {
                GregorianCalendar gc = new GregorianCalendar();
                gc.setTime(now);
                int hour = gc.get(Calendar.HOUR_OF_DAY);
                int minute = gc.get(Calendar.MINUTE);
//                boolean needExcute = true; //每10s执行 for test
                boolean needExcute = false;
                if (taskConfig.getExcuteFreq() == 0) {
                    //执行24点的任务,允许2分钟的误差
                    if (((hour == 24 || hour == 0) && minute <= 2) || (hour == 23 && minute >= 58)) {
                        needExcute = true;
                    }
                } else if (taskConfig.getExcuteFreq() == 1) {
                    //执行2点的任务
                    if ((hour == 2 && minute <= 2) || (hour == 1 && minute >= 58)) {
                        needExcute = true;
                    }
                } else if (taskConfig.getExcuteFreq() == 2) {
                    //执行4点的任务
                    if ((hour == 4 && minute <= 2) || (hour == 3 && minute >= 58)) {
                        needExcute = true;
                    }
                } else if (taskConfig.getExcuteFreq() == 3) {
                    //执行6点的任务
                    if ((hour == 6 && minute <= 2) || (hour == 5 && minute >= 58)) {
                        needExcute = true;
                    }
                }
                if (needExcute) {
                    //开始执行任务
                    logger.info("\n=====[  开始执行任务  ]=====\n\t[id:{},ip-port:{}-{}]", taskConfig.getId(), taskConfig.getIpAddress(), taskConfig.getPortNo());
                    new TaskExcuteThread(taskConfig).start();
                } else {
                    logger.info("\n=====[  任务未到点  ]=====\n\t[id:{},ip-port:{}-{}]", taskConfig.getId(), taskConfig.getIpAddress(), taskConfig.getPortNo());
                }
            }
        }
    }

    class TaskExcuteThread extends Thread {

        private TaskConfig taskConfig;

        public TaskExcuteThread(TaskConfig taskConfig) {
            this.taskConfig = taskConfig;
        }

        @Override
        public void run() {
            try {
                long start = System.currentTimeMillis();
                Map<String[], List<String[]>> openedTableColumn = TaskUtil.setWhiteNameList(taskConfig, true);
                if (openedTableColumn == null) {
                    logger.info("\n=====[  openedTableColumn为空,任务终止!  ]=====");
                    return;
                }
                if (!TaskUtil.insertComments(taskConfig)) {
                    logger.info("\n=====[  插入comments失败,任务终止!  ]=====");
                    return;
                }
                if (!TaskUtil.upLoad(taskConfig, true)) {
                    logger.info("\n=====[  上传失败,任务终止!  ]=====");
                    return;
                }
                long end = System.currentTimeMillis();
                logger.info("\n=====[  任务执行成功!<cost:{}ms>  ]=====",end-start);
            } catch (Exception e) {
                logger.info("\n=====[  任务执行异常!  ]=====\n{}", StringUtil.getExceptonStack(e));
            }
        }
    }

}
